﻿using System;
using System.Configuration;
using System.Xml.XPath;
using System.Xml.Serialization;
using System.Xml;

namespace suanpan.API.Components
{
    class XmlSerializerSectionHandler : IConfigurationSectionHandler
    {
        #region IConfigurationSectionHandler Members

        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            XPathNavigator nav = section.CreateNavigator();
            string typeName = (string)nav.Evaluate("string(@type)");
            Type t = Type.GetType(typeName);

            if ( t == null )
                throw new ConfigurationErrorsException(string.Format("Failed to create type {0}.", typeName), section);

            XmlSerializer configSerializer = new XmlSerializer(t);
            try
            {
                return configSerializer.Deserialize(new XmlNodeReader(section));
            }
            catch ( Exception ex )
            {
                if ( ex.InnerException != null )
                    throw ex.InnerException;

                throw ex;
            }
        }

        #endregion
    }
}
